<template>
  <main-content title="优惠券管理">
    <template #search-bar>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="优惠券名称">
            <el-input
              v-model="searchForm.couponDefineName"
              clearable
              placeholder="请输入优惠券名称"
            />
          </el-form-item>
          <el-form-item label="优惠券类型">
            <el-select
              v-model="searchForm.couponType"
              placeholder="请选择优惠券类型"
              clearable
            >
              <el-option
                v-for="item in CouponType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优惠券状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择优惠券状态"
              clearable
            >
              <el-option
                label="启用"
                :value="0"
              />
              <el-option
                label="禁用"
                :value="1"
              />
            </el-select>
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="research"
            >
              查询
            </el-button>
            <el-button
              v-has="['190101']"
              type="primary"
              icon="Plus"
              @click="toCreate"
            >
              新增
            </el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>

    <div class="statistics">
      领取
      <span class="highlight">{{ couponDefineStatics?.receiveNum }}</span>
      张，使用
      <span class="highlight">{{ couponDefineStatics?.usedNum }}</span>
      张，已过期
      <span class="highlight">{{ couponDefineStatics?.expiredNum }}</span>
      张
    </div>

    <LayoutTable
      ref="tableRef"
      url="merchant/coupon/pageCouponDefine"
      :param="searchForm"
    >
      <el-table-column
        label="优惠券ID"
        width="100"
        prop="id"
      />
      <el-table-column
        label="优惠券名称"
        min-width="140"
        prop="couponName"
      />
      <el-table-column
        label="优惠券类型"
        width="140"
      >
        <template #default="props">
          {{ getCouponTypeName(props.row.couponType) }}
        </template>
      </el-table-column>
      <el-table-column
        label="优惠券状态"
        width="120"
      >
        <template #default="props">
          <el-switch
            v-model="props.row.status"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="0"
            :inactive-value="1"
            :before-change="() => handleStatusChange(props.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="优惠券数量/领取量/使用量"
        width="210"
      >
        <template #default="{row}">
          {{ row?.couponTotalNum ?? '0' }} / {{ row?.couponReceiveNum ?? '0' }} / {{ row?.couponUseNum ?? '0' }}
        </template>
      </el-table-column>
      <el-table-column
        label="使用率"
        width="140"
        prop="usedRate"
      >
        <template #default="{row}">
          {{ (row?.usedRate ?? 0) + '%' }}
        </template>
      </el-table-column>
      <el-table-column
        label="领取时间"
        width="210"
      >
        <template #default="props">
          <div
            class="claim-time-range"
            :class="{'outof-claim-time-range': checkOutofTimeRange(props.row)}"
          >
            <div>{{ formatTime(props.row.receiveStartTime) }}至</div>
            <div>{{ formatTime(props.row.receiveEndTime) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        width="140"
        prop="createUserName"
      />
      <el-table-column
        label="更新时间"
        width="180"
      >
        <template #default="{row}">
          {{ formatTime(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="180"
      >
        <template #default="props">
          <el-button
            v-has="['190102']"
            type="primary"
            link
            @click="toEdit(props.row)"
          >
            编辑
          </el-button>
          <el-button
            v-has="['190103']"
            type="primary"
            link
            @click="copy(props.row)"
          >
            复制
          </el-button>
          <el-dropdown
            v-has="['190104', '190105', '190106']"
            @command="(command) => handleCommand(command, props.row)"
          >
            <el-button
              style="margin-left: 12px;"
              link
              type="primary"
            >
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- <el-dropdown-item
                  v-has="['190106']"
                  command="send_coupon_manually"
                >
                  手动发券
                </el-dropdown-item> -->
                <el-dropdown-item
                  v-has="['190104']"
                  command="export_claim_detail"
                >
                  导出领取明细
                </el-dropdown-item>
                <el-dropdown-item
                  v-has="['190105']"
                  command="delete_coupon"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </LayoutTable>
  </main-content>

  <export-data
    v-model:show-dialog="isShowExportDialog"
    :export-type="exportForm.beanName"
    :title="exportForm.title"
    :search-data="{
      couponId: exportForm.couponId
    }"
  />
</template>

<script setup lang="ts">
import type { ICouponManageRow } from "@/api/modules/marketingTool";
import moment from "moment";
import { useCouponType } from "@/views/marketingTool/compositions/useCouponType"
import { getCouponDefineStatics, deleteCouponDefine, updateCouponDefineStatus } from "@/api/marketingTool"


const router = useRouter()
const { getCouponTypeName, CouponType } = useCouponType()

const searchForm = reactive({
  couponDefineName: "",
  couponType: "",
  status: "",
})

const tableRef = ref();

const research = () => {
  tableRef.value.research();
}

watch(() => searchForm, () => {
  _getCouponDefineStatics(searchForm)
}, {deep: true})

const currentRow = ref();

// 新增
const toCreate = () => {
  console.log("新增！！！")
  router.push({
    path: 'coupon_manage/create'
  })
}

// 优惠券状态切换
const handleStatusChange: (row: ICouponManageRow) => Promise<boolean> = (row) => {
  console.log("状态切换！！！")
  return new Promise<boolean>((resolve) => {
    updateCouponDefineStatus({ 
      id: row.id,
      status: row.status === 1 ? 0 : 1 // 是否禁用 1 禁用 0 启用
    })
      .then(rs => {
        if (rs.code === 200) {
          resolve(true)
        } else {
          resolve(false)
        }
      })
  }).catch(e => {
    console.log(e)
    return Promise.resolve(false)
  })
}

// 领取时间
const formatTime = (timestamp: number) => {
  return timestamp ? moment(timestamp).format("YYYY.MM.DD HH:mm:ss") : ''
}

const checkOutofTimeRange = (row: ICouponManageRow) => {
  const now = +new Date();
  console.log('checkOutofTimeRange', now < row.receiveStartTime || now > row.receiveEndTime)
  return now < row.receiveStartTime || now > row.receiveEndTime
}

// 编辑
const toEdit = (row: ICouponManageRow) => {
  console.log("编辑！！！")
  router.push({
    path: 'coupon_manage/edit',
    query: {
      id: row.id
    }
  })
}

// 复制
const copy = async (row: ICouponManageRow) => {
  console.log("复制！！！")
  router.push({
    path: 'coupon_manage/edit',
    query: {
      id: row.id,
      action: "copy"
    }
  })
}

// 更多
const handleCommand = (command: string, row: ICouponManageRow) => {
  switch (command) {
    // case "send_coupon_manually": sendCouponManually(row);break;
    case "export_claim_detail": exportClaimDetail(row);break;
    case "delete_coupon": deleteCoupon(row);break;
    default: console.log("command not found");
  }
}

// 手动发券
// const sendCouponManually = (row: ICouponManageRow) => {
//   console.log("手动发券")
// }

// 导出领取明细
const isShowExportDialog = ref(false);
const exportForm = ref({
  beanName: "couponUserDetailExport", // 固定值 
  title: "",
  couponId: -1
})
const exportClaimDetail = (row: ICouponManageRow) => {
  currentRow.value = row;
  exportForm.value.title = "优惠券领取明细";
  exportForm.value.couponId = row.id
  isShowExportDialog.value = true
}

// 删除
const deleteCoupon = (row: ICouponManageRow) => {
  ElMessageBox.confirm("确认删除？", "提示").then(async () => {
    const rs = await deleteCouponDefine({ id: row.id })
    if (rs.code === 200) {
      ElMessage.success("删除成功")
      research()
    }
  }).catch(() => {
    void 0
  })
}

const couponDefineStatics = ref()
const _getCouponDefineStatics = async () => {
  const rs = await getCouponDefineStatics(searchForm)
  if (rs.code === 200) {
    couponDefineStatics.value = rs.payload
  }
}

onMounted(() => {
  _getCouponDefineStatics()
})
  
</script>

<style scoped lang="scss">
.statistics {
  margin-bottom: 18px;
  font-size: 14px;
  color: #333;

  .highlight {
    font-size: 16px;
    color: var(--el-color-primary);
  }
}

.claim-time-range {
  color: #606266;
}

.outof-claim-time-range {
  color: #bbb;
}
</style>